﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Microsoft.SharePoint;


namespace Eneta.Portal.Events
{
    public class EventControl : UserControl
    {
        protected Repeater _eventsRepeater;

        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    var events = GetEvents();
                    if (events.Rows.Count == 0)
                        return;
                    _eventsRepeater.DataSource = events;
                    _eventsRepeater.DataBind();
                }
                catch(Exception ex)
                {
                    Logger.LogWarning("OnLoad(): Error when loading control", GetType().ToString());
                    Logger.LogException(ex);
                }
            }
        }

        private static DataTable GetEvents()
        {
            var result = new DataTable();
            var siteId = SPContext.Current.Site.ID;

            var sec = new SPSecurity.CodeToRunElevated(delegate
                {
                    using (var site = new SPSite(siteId))
                    using (var web = site.OpenWeb("/uritused/"))
                    {
                        var list = web.Lists["Lehed"];

                        var items =
                            Query.GetItems(list,
                                           "<Where><Eq><FieldRef Name='ContentType'/><Value Type='Text'>Yritus</Value></Eq></Where><OrderBy><FieldRef Name='From' Ascending='False'/></OrderBy>",
                                           3, new[] { "Title", "Comments", "Location1", "From" });
                        if (items == null)
                            return;
                        FillResultSet(items, result);
                    }
                });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return result;
        }

        private static void FillResultSet(SPListItemCollection items, DataTable result)
        {
            if (items.Count == 0)
                return;
            result.Columns.Add("Month", typeof(string));
            result.Columns.Add("Day", typeof(int));
            result.Columns.Add("Title", typeof(string));
            result.Columns.Add("FullDate", typeof(string));
            result.Columns.Add("Location", typeof(string));
            result.Columns.Add("Description", typeof(string));
            result.Columns.Add("Url", typeof(string));
            foreach (SPListItem item in items)
            {
                var row = result.NewRow();
                if (item["Title"] != null)
                {
                    row["Title"] = item["Title"].ToString();
                }
                else
                {
                    row["Title"] = string.Empty;
                }
                if (item["Comments"] != null)
                {
                    row["Description"] = item["Comments"].ToString();
                }
                else
                {
                    row["Description"] = string.Empty;
                }
                if (item["From"] != null)
                {

                    var startDate = DateTime.Parse(item["From"].ToString());
                    row["Month"] = GetMonthName(startDate.Month);
                    row["Day"] = startDate.Day;
                    row["FullDate"] = startDate.ToShortDateString();

                }
                else
                {
                    row["Month"] = string.Empty;
                    row["Day"] = 0;
                    row["FullDate"] = string.Empty;
                }
                if (item["Location1"] != null)
                {
                    row["Location"] = item["Location1"].ToString();
                }
                else
                {
                    row["Location"] = string.Empty;
                }
                row["Url"] = "/uritused/" + item.Url;
                result.Rows.Add(row);
            }
        }

        private static string GetMonthName(int month)
        {
            switch (month)
            {
                case 1:
                    return "Jaanuar";
                case 2:
                    return "Veebruar";
                case 3:
                    return "Märts";
                case 4:
                    return "Aprill";
                case 5:
                    return "Mai";
                case 6:
                    return "Juuni";
                case 7:
                    return "Juuli";
                case 8:
                    return "August";
                case 9:
                    return "September";
                case 10:
                    return "Oktoober";
                case 11:
                    return "November";
                case 12:
                    return "Detsember";
            }
            return string.Empty;
        }
    }
}
